/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved.
 */

package com.guchenbo.hive;

import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * JDBCExample
 *
 * @author
 * @since 8.0.0
 */
@Slf4j
public class SparkThriftKerberosExample {

    public static final String HADOOP_SECURITY_AUTHENTICATION = "hadoop.security.authentication";
    public static final String HADOOP_SECURITY_AUTHENTICATION_VALUE = "kerberos";
    private static final String HIVE_DRIVER = "org.apache.hive.jdbc.HiveDriver";

    public static void main(String[] args) throws Exception {
        String principal = "simba-os";
        String keytab = "/Users/guchenbo/opt/etc/kerberos/dev02/keytab/simba-os.keytab";
        String krb5Conf = "/Users/guchenbo/opt/etc/kerberos/dev02/krb5.conf";
                        //"/etc/krb5.conf";
        loginKerberos(principal, keytab, krb5Conf);

        String jdbcPrincipal = "spark/dev-02-datakun-startdt-3@EXAMPLE.COM";
        Class.forName(HIVE_DRIVER);
        String jdbcUrl = "jdbc:hive2://172.31.1.33:10016/;principal=" + jdbcPrincipal;
        Connection connection = DriverManager.getConnection(jdbcUrl);
        System.out.println(connection);

        // hudi
        hudi(connection);

        connection.close();
    }

    private static void hudi(Connection connection) throws SQLException {
        String sql = "CREATE TABLE spark_hudi_t1 (`col0` int COMMENT 'col0',`col1` smallint COMMENT 'col1',`col2` bigint COMMENT 'col2',`col3` tinyint COMMENT 'col3',`col4` double COMMENT 'col4',`col5` float COMMENT 'col5',`col6` decimal COMMENT 'col6',`col7` string COMMENT 'col7',`col8` varchar(5) COMMENT 'col8',`col9` char(5) COMMENT 'col9',`col10` binary COMMENT 'col10',`col11` boolean COMMENT 'col11',`col12` timestamp COMMENT 'col12',`col13` date COMMENT 'col13',`ds` string COMMENT '') USING HUDI PARTITIONED BY (`col3`,`ds`)  COMMENT 'c';";

        sql="create table spark_t1(id int,name string, ds string) USING orc PARTITIONED BY (ds)  COMMENT 'c'";
        JDBCUtils.execDDL(connection,sql);
    }



    public static void loginKerberos(String principal, String keytab, String krb5Conf) throws IOException {
        System.setProperty("java.security.krb5.conf", krb5Conf);

        Configuration conf = new Configuration();
        conf.set(HADOOP_SECURITY_AUTHENTICATION, HADOOP_SECURITY_AUTHENTICATION_VALUE);
        UserGroupInformation.setConfiguration(conf);
        UserGroupInformation.loginUserFromKeytab(principal, keytab);
        System.out.println(UserGroupInformation.getLoginUser());
    }

}
